package cn.enited.devtools.apiaggregator.repo.impl;

import cn.enited.devtools.apiaggregator.consts.CommonConst;
import cn.enited.devtools.apiaggregator.consts.ErrorCode;
import cn.enited.devtools.apiaggregator.entity.Project;
import cn.enited.devtools.apiaggregator.exception.BizException;
import cn.enited.devtools.apiaggregator.repo.ProjectRepository;
import cn.enited.devtools.apiaggregator.utils.NumUtil;
import org.bson.Document;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Repository
public class ProjectRepositoryImpl extends AbstractRepository<Project> implements ProjectRepository {
    @Override
    public Class<Project> getEntityType() {
        return Project.class;
    }

    @Override
    public void save(Project entity) throws BizException {
        if (Objects.isNull(entity)) {
            throw new BizException(ErrorCode.NULL);
        }
        if (nameExists(entity)) {
            throw new BizException(ErrorCode.EXIST.code(), "项目名称已存在");
        }
        entity.preCreate();
        getMongoTemplate().save(entity);
    }

    @Override
    public void update(Project entity) throws BizException {
        if (Objects.isNull(entity)) {
            throw new BizException(ErrorCode.NULL);
        }
        if (nameExists(entity)) {
            throw new BizException(ErrorCode.EXIST.code(), "项目名称重复");
        }
        entity.preUpdate();
        Document fieldMap = entityToUpdateMap(entity, CommonConst.ENTITY.ID, CommonConst.ENTITY.BIZ_ID,
                CommonConst.ENTITY.CREATE_DATE, CommonConst.ENTITY.DEL_FLAG);
        Update update = Update.fromDocument(fieldMap);
        getMongoTemplate().updateFirst(getBizIdQuery(entity.getBizId()), update, Project.class);
    }

    @Override
    public List<String> getAllProjectNames() {
        Query query = Query.query(Criteria.where(CommonConst.ENTITY.DEL_FLAG).is(false));
        query.fields().include("name");
        return getMongoTemplate().find(query, Project.class).stream().map(Project::getName).collect(Collectors.toList());
    }

    private boolean nameExists(Project entity) {
        Criteria criteria = Criteria.where("name").is(entity.getName()).and(CommonConst.ENTITY.DEL_FLAG).is(false);
        if (NumUtil.isValidId(entity.getBizId())) {
            criteria.and(CommonConst.ENTITY.BIZ_ID).ne(entity.getBizId());
        }
        return exists(Query.query(criteria));
    }
}
